package com.zzxz.practicaltrainingsys.service.impl;

import com.zzxz.practicaltrainingsys.entity.ChatRecord;
import com.zzxz.practicaltrainingsys.mapper.ChatManageMapper;
import com.zzxz.practicaltrainingsys.service.ChatManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Transactional
public class ChatManageServiceImpl implements ChatManageService {

    @Autowired
    private ChatManageMapper chatManageMapper;

    @Override
    public List<ChatRecord> getAllChatRecords() {
        try {
            return chatManageMapper.selectAllChatRecords();
        } catch (Exception e) {
            throw new RuntimeException("获取聊天记录失败", e);
        }
    }

    @Override
    public List<ChatRecord> getGroupMessages(String inviteCode) {
        if (!StringUtils.hasText(inviteCode)) {
            throw new IllegalArgumentException("邀请码不能为空");
        }
        try {
            return chatManageMapper.selectGroupMessages(inviteCode);
        } catch (Exception e) {
            throw new RuntimeException("获取群聊消息失败", e);
        }
    }

    @Override
    public int deleteChatRecord(Long id) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("聊天记录ID无效");
        }
        try {
            return chatManageMapper.deleteChatRecordById(id);
        } catch (Exception e) {
            throw new RuntimeException("删除聊天记录失败", e);
        }
    }

    @Override
    public int batchDeleteChatRecords(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new IllegalArgumentException("删除的ID列表不能为空");
        }
        // 验证ID的有效性
        for (Long id : ids) {
            if (id == null || id <= 0) {
                throw new IllegalArgumentException("存在无效的聊天记录ID: " + id);
            }
        }
        try {
            return chatManageMapper.batchDeleteChatRecords(ids);
        } catch (Exception e) {
            throw new RuntimeException("批量删除聊天记录失败", e);
        }
    }

    @Override
    public int deleteGroupChat(String inviteCode) {
        if (!StringUtils.hasText(inviteCode)) {
            throw new IllegalArgumentException("邀请码不能为空");
        }
        try {
            return chatManageMapper.deleteGroupChatByInviteCode(inviteCode);
        } catch (Exception e) {
            throw new RuntimeException("删除群聊失败", e);
        }
    }

    @Override
    public int clearOldMessages(int days) {
        if (days <= 0) {
            throw new IllegalArgumentException("清理天数必须大于0");
        }
        try {
            LocalDateTime cutoffTime = LocalDateTime.now().minusDays(days);
            return chatManageMapper.clearOldMessages(cutoffTime);
        } catch (Exception e) {
            throw new RuntimeException("清理历史消息失败", e);
        }
    }

    @Override
    public int saveChatRecord(ChatRecord chatRecord) {
        if (chatRecord == null) {
            throw new IllegalArgumentException("聊天记录不能为空");
        }

        // 验证必填字段
        if (!StringUtils.hasText(chatRecord.getUsername())) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        if (!StringUtils.hasText(chatRecord.getContent())) {
            throw new IllegalArgumentException("消息内容不能为空");
        }
        if (!StringUtils.hasText(chatRecord.getChatType())) {
            throw new IllegalArgumentException("聊天类型不能为空");
        }

        // 设置默认值
        if (chatRecord.getCreateTime() == null) {
            chatRecord.setCreateTime(LocalDateTime.now());
        }
        if (chatRecord.getInviteCode() == null) {
            chatRecord.setInviteCode("0"); // 公共聊天默认为0
        }

        try {
            return chatManageMapper.insertChatRecord(chatRecord);
        } catch (Exception e) {
            throw new RuntimeException("保存聊天记录失败", e);
        }
    }

    @Override
    public List<ChatRecord> searchChatRecords(String userType, String chatType,
                                              String username, String inviteCode, String keyword) {
        try {
            // 处理空字符串，转为null以便SQL正确处理
            userType = StringUtils.hasText(userType) ? userType.trim() : null;
            chatType = StringUtils.hasText(chatType) ? chatType.trim() : null;
            username = StringUtils.hasText(username) ? username.trim() : null;
            inviteCode = StringUtils.hasText(inviteCode) ? inviteCode.trim() : null;
            keyword = StringUtils.hasText(keyword) ? keyword.trim() : null;

            return chatManageMapper.searchChatRecords(userType, chatType, username, inviteCode, keyword);
        } catch (Exception e) {
            throw new RuntimeException("搜索聊天记录失败", e);
        }
    }

    @Override
    public ChatRecord getChatRecordById(Long id) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("聊天记录ID无效");
        }
        try {
            return chatManageMapper.selectChatRecordById(id);
        } catch (Exception e) {
            throw new RuntimeException("获取聊天记录失败", e);
        }
    }
}